<?php


namespace App\Service\Store;


use App\Constants\Coupon;
use App\Dao\BusinessDao;
use App\Dao\BusinessIndustryDao;
use App\Dao\CouponDao;
use App\Service\Service;
use Hyperf\Di\Annotation\Inject;

/**
 * 优惠券服务
 * @author 陈奕文
 * @package App\Service\Store
 */
class CouponService extends Service
{

    /**
     * 优惠券Dao
     * @Inject()
     * @var CouponDao
     */
    public $dao;

    /**
     * 商家Dao
     * @Inject()
     * @var BusinessDao
     */
    public $business_dao;

    /**
     * 商家行业Dao
     * @Inject()
     * @var BusinessIndustryDao
     */
    public $business_industry_dao;

    public function getCouponList(array $params)
    {
        $map = [];
        isset($params['start_time']) && !isset($params['end_time'])  && !empty($params['start_time']) && $map['created_at'] = ['>=', strtotime($params['start_time'])]; // 创建开始时间
        isset($params['end_time']) &&  !isset($params['start_time'])  && !empty($params['end_time']) && $map['created_at'] = ['<=', strtotime($params['end_time'])]; // 创建结束时间

        isset($params['end_time']) &&  isset($params['start_time']) &&
        !empty($params['end_time']) && !empty($params['start_time']) &&
        $map['between_field'] = ['created_at' =>[strtotime($params['start_time']), strtotime($params['end_time'])]]; // 有创建开始和结束时间

        isset($params['status']) && $map['status'] = (int)$params['status']; // 状态/0禁用/1正常/2拒绝
        isset($params['type']) && $map['type'] = (int)$params['type']; // 优惠券类型/1=折扣券(优惠券)/2=现金抵用券/3=全店打折
        isset($params['search']) && !empty($params['search']) && $map['title'] = ['like', "%{$params['search']}%"]; // 姓名

        $sort = 'id desc';
        // 分页
        $page_size = null;
        if (isset($params['page'])) {
            $page_size = 10;
            isset($params['page_size']) && !empty($page_size) && $page_size = (int)$params['page_size'];
        }

        $select = ['id', 'business_id','created_at', 'type', 'picture', 'title', 'description', 'goods_price', 'price', 'reach_price', 'instructions', 'stock', 'sales', 'status'];
        if (isset($map['type']) && $map['type'] != 3) {
            $appends = ['start_time', 'expire_time', 'expire_type'];
            $select = array_merge($select, $appends);
        }

        $coupon_list = $this->dao->getCouponsByMapSelect($map, $sort, $select,$page_size)->toArray();
        if (isset($coupon_list['data'])) {
            $coupon_list['data'] = $this->joinMallIndustryData($coupon_list['data']);
        } else {
            $coupon_list = $this->joinMallIndustryData($coupon_list);
        }

        return $coupon_list;
    }

    /**
     * 拼接店铺与行业数据
     * @param array $coupon_list
     * @return array
     */
    public function joinMallIndustryData(array $coupon_list)
    {
        // 相关商家信息
        $business_ids = array_unique(array_column($coupon_list, 'business_id'));
        $businees_select = ['id', 'industry_id', 'name', 'logo'];
        $business_map['id'] = ['in', $business_ids];
        $businesses = $this->business_dao->Many($business_map, $businees_select);
        // 商家行业 名称 logo
        $biz_ind_ids = $businesses->pluck('industry_id', 'id')->toArray();
        $biz_names = $businesses->pluck('name', 'id')->toArray();
        $biz_logos = $businesses->pluck('logo', 'id')->toArray();
        // 相关行业信息
        $businesses = $businesses->toArray();
        $industry_ids = array_unique(array_column($businesses, 'industry_id')) ;
        // 行业名称
        $industry_names = $this->business_industry_dao->getBusinessNameByIds($industry_ids)->toArray();

        foreach ($coupon_list as $key => &$item) {
            $ind_id = $biz_ind_ids[$item['business_id']]??null; // 行业ID
            $item['industry_id'] = $ind_id??0;

            $item['biz_name'] = $biz_names[$item['business_id']]??""; // 商家名称
            $item['biz_logo'] = $biz_logos[$item['business_id']]??""; // 商家logo
            $item['industry_name'] = $industry_names[$ind_id]??""; // 行业名称

            $item['create_time'] = date("Y-m-d H:i:s", (int)$item['created_at']); // 提交时间
            $item['status_text'] = Coupon::STATUS_LIST[$item['status']]??'无'; // 状态（中文）
        }

        return $coupon_list;
    }

    /**
     * id通过
     * @param array $ids
     * @return mixed
     */
    public function passByIds(array $ids)
    {
        empty($ids) && $this->error('COUPON.NOT_HAVE_COUPON');
        $data = [
          'passed' => [
              'pass_ids' => [],
              'pass_show' => "审核成功",
          ],
            'failed' => [
              'fail_ids' =>[],
              'fail_show' => '优惠券对应商家还未审核或未通过',
            ],
            'no_exist' => [
              'no_ids' => [],
              'no_show' => '优惠券不存在',
            ],
        ];
        // 优惠券正常商家
        $coupons = $this->dao->getCouponsByMapSelect([
            'id' => ['in', $ids],
        ], null, ['id', 'business_id']);

        //  所有优惠券id对应的商家id
        $biz_ids = $coupons->pluck('business_id', 'id')->toArray();

        foreach ($ids as $coupon_id) {
          if (!isset($biz_ids[$coupon_id])) { // 过滤查询不到的
              $data['no_exist']['no_ids'][] = $coupon_id;
          }
        }

        $biz = $coupons->toArray();
        $business_ids = array_unique(array_column($biz, 'business_id')); // 优惠券对应的商家IDs

        // 过滤的商家
        $filter_biz = $this->business_dao->Many([
            'id' => ['in', $business_ids],
            'status' => 1,
        ], ['id'])->toArray();

        // 过滤的商家ID
        $filter_biz_ids = array_column($filter_biz, 'id');

        // 查询里面ID在过滤过的优惠券ID
        foreach ($biz_ids as $coupon_id => $biz_id) {
            if (in_array($biz_id, $filter_biz_ids)) {
                $data['passed']['pass_ids'][] = $coupon_id; // 通过优惠券
            } else {
                $data['failed']['fail_ids'][] = $coupon_id; // 未通过优惠券
            }
        }
//        return $data;
        $result = $this->dao->update([
            'id' => ['in', $data['passed']['pass_ids']],
        ], ['status' => 1 ]);
        !$result && $this->error("COUPON.FAIL_UPDATE_PASS");

        return $data;
    }

}